package cn.azzhu.day03;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.util.Collector;

/**
 * @author azzhu
 * @create 2020-09-17 21:27:12
 */
public class AddSinkDemo {
    public static void main(String[] args) throws Exception {
        //todo 1.创建执行环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //todo 2.创建DataStream --source
        final DataStream<String> lines = env.socketTextStream(args[0], Integer.parseInt(args[1]));

        //todo 3.数据处理

        final SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {
                final String[] words = line.split(" ");
                for (String word : words) {
                    final Tuple2<String, Integer> tp = Tuple2.of(word, 1);
                    out.collect(tp);
                }
            }
        });

        final SingleOutputStreamOperator<Tuple2<String, Integer>> summed = wordAndOne.keyBy(0).sum(1);

        summed.addSink(new SinkFunction<Tuple2<String, Integer>>() {
            @Override
            public void invoke(Tuple2<String, Integer> value, Context context) throws Exception {
                System.out.println(value);
            }
        });

        //todo 4.启动,异常不要捕获，交个flink去处理
        env.execute("AddSinkDemo");
    }
}
